import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import selenium.webdriver.support.ui as ui
import logging

class SaveEmail():
    login_url = 'http://mail.eyes-control.com/webmail7.5/webmail.php?r=site/index/domain/eyes-control.com'
    def __init__(self, username, password):
        self.username = username
        self.password = password
        chrome_options = webdriver.ChromeOptions()
        # chrome_options.add_argument('--proxy-server=%s' % 'http://116.196.85.166:3128')
        # 修改文件保存路径
        save_dir = os.path.join('/media/ubuntu/08f29263-3882-43db-96fd-febb6f2e2e5f/mail_data', username)
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        # 设置禁止加载图片
        prefs = {"profile.managed_default_content_settings.images":2, 'download.default_directory': save_dir}
        chrome_options.add_experimental_option("prefs", prefs)
        self.browser = webdriver.Chrome(chrome_options=chrome_options)

    # 用户登录，进入邮箱主页
    def login(self):
        self.browser.get(self.login_url)
        username_input_xpath = '//*[@id="username"]'
        password_input_xpath = '//*[@id="secretkeyshow"]'
        login_button_xpath = '//*[@id="login_submit_btn"]'
        # 输入用户名
        self.browser.find_element_by_xpath(username_input_xpath).send_keys(self.username)
        # 输入密码
        self.browser.find_element_by_xpath(password_input_xpath).send_keys(self.password)
        # 点击登录按钮
        self.browser.find_element_by_xpath(login_button_xpath).click()

    # 等待元素加载完成
    def wait_element(self, xpath_str):
        # 最长等待时间为300s
        wait = ui.WebDriverWait(self.browser, 300)
        wait.until(lambda driver: self.browser.find_element_by_xpath(xpath_str))

    # 获取所有历史邮件
    def get_history_mail(self):
        get_all_year_xpath = '//*[@id="sideMenu"]/div[2]/ul/li[11]/a'
        # 显示所有年份
        self.browser.find_element_by_xpath(get_all_year_xpath).click()
        year_xpath = '//*[@id="sideMenu"]/div[2]/ul/li[11]/ul/li/ul/li/a'
        time.sleep(2)
        list_year = self.browser.find_elements_by_xpath(year_xpath)
        # print(list_year)
        for year in list_year[1:]:
            js = year.get_attribute("onclick")
            # 加载每个月的邮箱
            self.browser.execute_script(js)
            time.sleep(1)
            self.next_page()

    # 下载邮件并判断是否有下一页，有下一页则继续下载
    def next_page(self):
        list_mail_xpath = '//*[@id="__p8_list_main"]/div/table/tbody/tr'
        mail_length = len(self.browser.find_elements_by_xpath(list_mail_xpath))
        # for i in range(2, mail_length): # 0,1 不是邮件
        #     # 进入一封邮件，并切换到邮件窗口
        #     self.switch_window(list_mail_xpath, i)
        #     show_save_element_xpath = 'id("layout_top")/div[2]/a[8]'
        #     try:
        #         self.wait_element(show_save_element_xpath)
        #     except Exception as e:
        #         # 关闭当前窗口
        #         self.close_window()
        #         # 进入一封邮件，并切换到邮件窗口
        #         self.switch_window(list_mail_xpath, i)
        #         self.wait_element(show_save_element_xpath)
        #     # 点击更多
        #     self.browser.find_element_by_xpath(show_save_element_xpath).click()
        #     # 导出邮件
        #     save_xpath = '//div[@class="address_tip_menu"]/ul/li[@class="li_underline"]/a'
        #     save_button = self.browser.find_element_by_xpath(save_xpath).click()
        #     # 关闭当前窗口
        #     self.close_window()

        next_page_xpath = '//*[@id="__p8_list_bottom"]/div/div[2]/a[3]'
        time.sleep(2)
        next_page_class = self.browser.find_element_by_xpath(next_page_xpath).get_attribute("class")
        # 判断是否是最后一页
        if 'disabled' not in next_page_class:
            self.browser.find_element_by_xpath(next_page_xpath).click()
            self.next_page()

    def close_window(self):
        self.browser.switch_to_default_content()
        close_xpath = '//*[@id="navigateArea"]/div/div[2]/ul/li[@class="tab_item active"]/a'
        self.wait_element(close_xpath)
        self.browser.find_element_by_xpath(close_xpath).click()
    
    # 进入一封邮件，并切换到邮件窗口
    def switch_window(self, list_mail_xpath, i):
        time.sleep(2)
        self.browser.find_elements_by_xpath(list_mail_xpath)[i].click()
        # 点击更多操作，动态加载导出邮件按钮
        self.wait_element('//iframe')
        iframe_id = self.browser.find_element_by_xpath('//iframe').get_attribute("id")
        # # 切换到当前iframe
        self.browser.switch_to_frame(iframe_id)

if __name__ == '__main__':
    username = 'chenwei'
    password = 'asdf1234?'
    email = SaveEmail(username, password)
    email.login()
    email.get_history_mail()